﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace harness
{
    public class Client
    {
        private readonly string baseUrl;
        private readonly int tasks;
        private ConcurrentQueue<string> result;
        
        public Client(string baseUrl, int tasks)
        {
            this.baseUrl = baseUrl;
            this.tasks = tasks;
            this.result = new ConcurrentQueue<string>();
        }
        public void Start()
        {
            Task[] tasks = new Task[this.tasks];

            for (int i = 0; i < this.tasks; ++i)
            {
                tasks[i] = this.Perform(i);
            }

            Task.WaitAll(tasks);

            result.ToList().ForEach(Console.WriteLine);
        }
        public async Task Perform(int state)
        {
            string url = String.Format("{0}{1}", this.baseUrl, state.ToString().PadLeft(3, '0'));
            var client = new HttpClient();
            Stopwatch timer = new Stopwatch();

            timer.Start();
            string result = await client.GetStringAsync(url);
            timer.Stop();

            this.result.Enqueue(String.Format("{0,4}\t{1,5}\t{2}", url, timer.ElapsedMilliseconds, result));
        }

        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = int.MaxValue;
            Client program = new Client(args[0], Int32.Parse(args[1]));
            program.Start();
        }
    }
}
